﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Data.OleDb;
using System.IO;
using System.Globalization;


namespace DiaryPlanner
{
    public partial class Diary_main : UserControl
    {


        //public int mod_flag; //해당 날짜에 데이터가 있는지 확인하는 flag
        private int load_flag; // 저장되어있는 data가 있는지에 대해서 확인하고 그에 맞게 interface를 구성하기 위한 flag
        private MainForm object_main;
        private bool del_check_value = false;
        public string pic_or_photo;
        public int check_photo_draw;
        

        Color yellow = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(128)))));
        Color blue = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(255)))), ((int)(((byte)(255)))));
        Color green = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(255)))), ((int)(((byte)(128)))));
        Color pink = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));


        public Diary_main(MainForm object_main_form)
        {
            
            InitializeComponent();
            check_photo_draw = 0;
            init_dairy();//현재 날짜에 저장되어 있는 diary를 불러온다. 없으면 빈칸으로 초기화
            object_main = object_main_form;
            new_pic_photo_add();
        }

        /// <summary>
        /// 처음 폴더를 생성시키는 함수
        /// </summary>
        private void new_pic_photo_add()
        {
            try//Picture_photo 폴더 생성
            {
                // If the directory doesn't exist, create it.
                if (!Directory.Exists("UserImage/" + UserProfile.Instance().userId + "/Picture_photo"))
                {
                    Directory.CreateDirectory("UserImage/" + UserProfile.Instance().userId + "/Picture_photo");
                }
            }
            catch (Exception)
            {
                // Fail silently
            }
        }

        /// <summary>
        /// 환경설정에 맞춰 스킨 설정
        /// </summary>
        public void skinSet()
        {
            string skin = UserProfile.Instance().setting;
            if (skin == "b")
            {
                this.BackColor = System.Drawing.Color.PaleTurquoise;
                this.select_year_text_box.BackColor = System.Drawing.Color.PaleTurquoise;
                this.select_month_text.BackColor = System.Drawing.Color.PaleTurquoise;
                this.select_day_text.BackColor = System.Drawing.Color.PaleTurquoise;
                this.textBox1.BackColor = System.Drawing.Color.PaleTurquoise;
                this.textBox3.BackColor = System.Drawing.Color.PaleTurquoise;
                this.textBox5.BackColor = System.Drawing.Color.PaleTurquoise;

            }
            else if (skin == "c")
            {
                this.BackColor = System.Drawing.Color.LawnGreen;
                this.select_year_text_box.BackColor = System.Drawing.Color.LawnGreen;
                this.select_month_text.BackColor = System.Drawing.Color.LawnGreen;
                this.select_day_text.BackColor = System.Drawing.Color.LawnGreen;
                this.textBox1.BackColor = System.Drawing.Color.LawnGreen;
                this.textBox3.BackColor = System.Drawing.Color.LawnGreen;
                this.textBox5.BackColor = System.Drawing.Color.LawnGreen;
            }
            else if (skin == "d")
            {
                this.BackColor = System.Drawing.Color.MistyRose;
                this.select_year_text_box.BackColor = System.Drawing.Color.MistyRose;
                this.select_month_text.BackColor = System.Drawing.Color.MistyRose;
                this.select_day_text.BackColor = System.Drawing.Color.MistyRose;
                this.textBox1.BackColor = System.Drawing.Color.MistyRose;
                this.textBox3.BackColor = System.Drawing.Color.MistyRose;
                this.textBox5.BackColor = System.Drawing.Color.MistyRose;
            }
            else
            { //skin=="a"
                this.BackColor = System.Drawing.SystemColors.ControlLight;
                this.BackColor = System.Drawing.SystemColors.ControlLight;
                this.select_year_text_box.BackColor = System.Drawing.SystemColors.ControlLight;
                this.select_month_text.BackColor = System.Drawing.SystemColors.ControlLight;
                this.select_day_text.BackColor = System.Drawing.SystemColors.ControlLight;
                this.textBox1.BackColor = System.Drawing.SystemColors.ControlLight;
                this.textBox3.BackColor = System.Drawing.SystemColors.ControlLight;
                this.textBox5.BackColor = System.Drawing.SystemColors.ControlLight;

            }
        }
        
        /// <summary>
        /// 처음 diary main화면 초기화 함수
        /// data base에서 현재 날짜의 data 확인
        /// </summary>
        private void init_dairy()
        {
            DateTime myDT = monthCalendar1.SelectionStart;
            this.select_year_text_box.Text = myDT.Year.ToString();
            this.select_month_text.Text = myDT.Month.ToString();
            this.select_day_text.Text = myDT.Day.ToString();
            load_db();
        }


        
        /// <summary>
        /// diary main화면의 버튼을 상태에 맞게 변경과 이미지를 띄워주는 함수
        /// filename = 이미지의 이름
        /// </summary>
        /// <param name="filename"></param>
        public void update_view(string filename)
        {
            this.daily_diary_text_add_button.Visible = false;
            this.daily_diary_text.Visible = true;
            this.mod_diary_button.Visible = true;
            this.del_diary_button.Visible = true;
            this.photo_visible_btn.Visible = true;
            if (check_photo_draw == 1)
            {
                this.picOrphoto_view.Image = Image.FromFile(Application.StartupPath + "/UserImage/" + UserProfile.Instance().userId + "/Picture_photo/" + filename);
            }
        }

        //////// 일기장을 db에서 삭제하였을때 해당하는 화면을 출력
        public void remove_view()
        {
            this.daily_diary_text.Text = "";
            //this.new_diary_button.Visible = true;
            this.daily_diary_text_add_button.Visible = true;
            this.photo_visible_btn.Visible = false;
            this.photo_no_visible_btn.Visible = false;
            this.daily_diary_text.Visible = false;
            this.mod_diary_button.Visible = false;
            this.del_diary_button.Visible = false;
        }

        //////////////////////////////////////////////////////////
        /////////db에서 불러온 data에 맞게 view를 설정/////////////
        //////////////////////////////////////////////////////////
        /// <summary>
        /// db에서 불러온 data에 맞게 view를 설정
        /// diary_text = diary내용
        /// align = 정렬상탱
        /// emotion = 기분 상태
        /// image_filename = 저장된 사진의 file 이름
        /// </summary>
        /// <param name="diary_text"></param>
        /// <param name="align"></param>
        /// <param name="emotion"></param>
        /// <param name="image_filename"></param>
        private void add_diary(string diary_text , string align, string emotion , string image_filename)
        {
            this.daily_diary_text.Text = diary_text;
            emotion_setting(emotion);
            align_setting(align);
            
            if (load_flag == 0)
            {
                this.daily_diary_text_add_button.Visible = true;
                this.photo_no_visible_btn.Visible = false;
                this.photo_visible_btn.Visible = false;
                this.daily_diary_text.Visible = false;
                this.mod_diary_button.Visible = false;
                this.del_diary_button.Visible = false;
                
            }
            else if(load_flag == 1)
            {
                this.daily_diary_text_add_button.Visible = false;
                this.daily_diary_text.Visible = true;
                this.photo_visible_btn.Visible = true;
                this.photo_no_visible_btn.Visible = false;
                this.mod_diary_button.Visible = true;
                this.del_diary_button.Visible = true;
                if (image_filename != null)
                {
                    this.picOrphoto_view.Image = Image.FromFile(Application.StartupPath + "/UserImage/" + UserProfile.Instance().userId + "/Picture_photo/" + image_filename);
                }
                //this.picOrphoto_view.BackColor = Color.Black;
                
            }
        }

        private void emotion_setting(string emotion)
        {
            if (emotion == "0")
            {
                this.emotion_view.Image = global::DiaryPlanner.Properties.Resources.smile_big;
            }
            else if(emotion == "1")
            {
                this.emotion_view.Image = global::DiaryPlanner.Properties.Resources.sad_big;
                
            }
            else if (emotion == "2")
            {
                this.emotion_view.Image = global::DiaryPlanner.Properties.Resources.soso_big;
            }
            else
            {
                this.emotion_view.Image = global::DiaryPlanner.Properties.Resources.angry_big;
            }
        }
        private void align_setting(string align)
        {
            if (align == "0")
            {
                this.daily_diary_text.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
            }
            else if (align == "1")
            {
                this.daily_diary_text.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
            }
            else
            {
                this.daily_diary_text.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
            }
        }
        //////////////////////설정 종료//////////////////////////////////
        ////////////////////////////////////////////////////////////////

        
        //new_diary or mod_diary 에서 적용된 textbox의 내용 및 속성값을 적용
        public void write_text_value(TextBox text_value)
        {
            this.daily_diary_text.Text = text_value.Text;
            this.daily_diary_text.TextAlign = text_value.TextAlign;
            this.daily_diary_text.Visible = true;
            this.daily_diary_text_add_button.Visible = false;
        }

        //new_diary or mod_diary 에서 적용된 기분과 날씨의 정보를 적용
        public void update_emotion(int emotion , int weather)
        {
            if (emotion == 0)
            {
                this.emotion_view.Image = global::DiaryPlanner.Properties.Resources.smile_big;
            }
            else if (emotion == 1)
            {
                this.emotion_view.Image = global::DiaryPlanner.Properties.Resources.sad_big;
            }
            else if (emotion == 2)
            {
                this.emotion_view.Image = global::DiaryPlanner.Properties.Resources.soso_big;
            }
            else
            {
                this.emotion_view.Image = global::DiaryPlanner.Properties.Resources.angry_big;
            }

            if (weather == 0)
            {
                this.weather_view.Image = global::DiaryPlanner.Properties.Resources.serenity_big;
            }
            else if (weather == 1)
            {
                this.weather_view.Image = global::DiaryPlanner.Properties.Resources.cloud_big;
            }
            else if (weather == 2)
            {
                this.weather_view.Image = global::DiaryPlanner.Properties.Resources.rain_big;
            }
            else
            {
                this.weather_view.Image = global::DiaryPlanner.Properties.Resources.snow_big;
            }
        }
      

        ////////////////////////////////////////////////////
        ////////////////////선택된 날짜의 연,월,일 저장된 text 넘김,/////////////
        ////////////////////////////////////////////////////
        public string load_year_value()
        {
            return this.select_year_text_box.Text;
        }
        public string load_month_value()
        {
            return this.select_month_text.Text;
        }
        public string load_day_value()
        {
            return this.select_day_text.Text;
        }
        public TextBox load_dialy_text()
        {
            return daily_diary_text;
        }
        ////////////////////////////////////////////////////

        public void dispose_imgae()
        {
            MessageBox.Show("dfdfdfdf");
           // this.picOrphoto_view.Image = null;
            MessageBox.Show("shit");
            this.picOrphoto_view.Image.Dispose();
            MessageBox.Show("fuck");
        }

        private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
        {
            
            DateTime myDT = monthCalendar1.SelectionStart;
            this.select_year_text_box.Text = myDT.Year.ToString();
            this.select_month_text.Text = myDT.Month.ToString();
            this.select_day_text.Text = myDT.Day.ToString();
            
            load_db((myDT.Year.ToString()+myDT.Month.ToString()+myDT.Day.ToString()));
            
            object_main.return_panel_size();

            this.daily_diary_text.Location = new System.Drawing.Point(251, 44);
            this.mod_diary_button.Location = new System.Drawing.Point(577, 395);
            this.del_diary_button.Location = new System.Drawing.Point(651, 395);
            this.Size = new System.Drawing.Size(778, 449);

            this.photo_no_visible_btn.Visible = false;
            this.photo_visible_btn.Visible = true;
            this.picOrphoto_view.Visible = false;

        }

        // 새로운 내용을 입력하기 위해 삽입 버튼을 누르면 new_diary 창을 생성하는 이벤트
        private void new_diary_button_Click(object sender, EventArgs e)
        {
            

            DateTime myDT = monthCalendar1.SelectionStart;
            
                Diary.new_diary new_form_diary = new Diary.new_diary(this);
                new_form_diary.ShowDialog();
            
        }

        // 저장되어 있는 diary를 수정하기 위한 module을 실행하는 이벤트
        private void mod_diary_button_Click(object sender, EventArgs e)
        {
            //mod_flag = 2;
            Diary.mod_diary mod_form_diary = new Diary.mod_diary(this);
            mod_form_diary.ShowDialog();
        }

        private void del_diary_button_Click(object sender, EventArgs e)
        {
            Diary.diary_del del_form_dialy = new Diary.diary_del(this);
            del_form_dialy.ShowDialog();
            if (del_check_value == true)
            {
                this.picOrphoto_view.Image = null;
                //this
            }
            /*else
            {

            }*/
        }

        private void daily_diary_text_add_button_Click(object sender, EventArgs e)
        {
            DateTime myDT = monthCalendar1.SelectionStart;

            Diary.new_diary new_form_diary = new Diary.new_diary(this);
            new_form_diary.ShowDialog();
        }

        /// <summary>
        /// 사진 or 그림 파일을 볼 수 있도록 window size를 확대
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void photo_visible_btn_Click(object sender, EventArgs e)
        {
            object_main.panel_size();

            this.daily_diary_text.Location = new System.Drawing.Point(251, 244);
            this.mod_diary_button.Location = new System.Drawing.Point(620, 592);
            this.del_diary_button.Location = new System.Drawing.Point(694, 592);
            this.Size = new System.Drawing.Size(778, 649);
            this.photo_visible_btn.Visible = false;
            this.photo_no_visible_btn.Visible = true;
            this.picOrphoto_view.Visible = true;
        }
        /// <summary>
        /// 사진 or 그림 파일을 볼 수 있는 window size를 축소
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void photo_no_visible_btn_Click(object sender, EventArgs e)
        {
            object_main.return_panel_size();

            this.daily_diary_text.Location = new System.Drawing.Point(251, 44);
            this.mod_diary_button.Location = new System.Drawing.Point(620, 392);
            this.del_diary_button.Location = new System.Drawing.Point(694, 392);
            this.Size = new System.Drawing.Size(778, 449);

            this.photo_no_visible_btn.Visible = false;
            this.photo_visible_btn.Visible = true;
            this.picOrphoto_view.Visible = false;
        }

        //////////////////////////////////////////////////////////
        ///////////현재 날짜의 data를 data base에서 load///////////
        /////////////////////////////////////////////////////////
        private void load_db()
        {
            try //예외처리문
            {
                string connectionString = "provider=Microsoft.JET.OLEDB.4.0;" //연결하는 객체의 공급자명(확장자명)
                                        + "data source = "  //데이터 소스=(경로입력하라는거)
                                        + Application.StartupPath ///상대경로 읽어옴
                                        + @"\diaryplannerdb.mdb";//실제 데이터베이스 파일이름

                string commandString = "Select * from [diary]";//diary테이블에 있는 모든필드들을 모두 검색해라.

                OleDbDataAdapter DBAdapter ////DataSet을 채우고 데이터 소스를 업데이트하는 데 사용되는 데이터 명령 집합 및 데이터베이스 연결하게 하는 함수
                    = new OleDbDataAdapter(commandString, connectionString);//connectionString이라는 경로와 쿼리명령을 동적할당

                OleDbCommandBuilder myCommandBuilder ///연결된 데이터베이스에서 DataSet의 변경 내용을 조정하는 데 사용되는 단일 테이블 명령을 자동으로 생성합니다
                    = new OleDbCommandBuilder(DBAdapter);

                DataSet DS = new DataSet(); //DS라는 데이터 셋 동적할당

                DBAdapter.Fill(DS, "diary"); //DS라는 데이터셋에 새로운 diary 테이블에 추가 또는 갱신하겠다고 알림.

                DataTable aTable = DS.Tables["diary"];//home테이블을 불러와 aTable을 새로 생성해서 저장

                if (aTable.Rows.Count == 0)
                {
                    load_flag = 0;
                    add_diary("", "0", "0", "");
                }

                for (int i = 0; i < aTable.Rows.Count; i++)
                {
                    int detect = String.Compare((System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + UserProfile.Instance().userId), aTable.Rows[i].ItemArray[0].ToString());

                    if (detect == 0)
                    {
                        load_flag = 1;
                        add_diary(aTable.Rows[i].ItemArray[1].ToString(), aTable.Rows[i].ItemArray[5].ToString(), aTable.Rows[i].ItemArray[2].ToString(), aTable.Rows[i].ItemArray[6].ToString()); //저장되어있는 data에 따라서 interface를 설정
                        break;
                    }
                }

            }
            catch (DataException DE) //DataException에러 발생확인하는 catch문
            {
                MessageBox.Show(DE.Message); //DataExpception 에러 발생시 메세지박스로 에러값을 출력해라.
            }
            catch (Exception DE) //Exception에러 발생확인하는 catch문
            {
                MessageBox.Show(DE.Message);//Expception 에러 발생시 메세지박스로 에러값을 출력해라.
            }
        }


        //////////////////////////////////////////////////////////
        ///////////선택된 날짜의 data를 data base에서 load/////////
        /////////////////////////////////////////////////////////
        private void load_db(string select_date)
        {
            try //예외처리문
            {
                string connectionString = "provider=Microsoft.JET.OLEDB.4.0;" //연결하는 객체의 공급자명(확장자명)
                                        + "data source = "  //데이터 소스=(경로입력하라는거)
                                        + Application.StartupPath ///상대경로 읽어옴
                                        + @"\diaryplannerdb.mdb";//실제 데이터베이스 파일이름

                string commandString = "Select * from [diary]";//diary테이블에 있는 모든필드들을 모두 검색해라.

                OleDbDataAdapter DBAdapter ////DataSet을 채우고 데이터 소스를 업데이트하는 데 사용되는 데이터 명령 집합 및 데이터베이스 연결하게 하는 함수
                    = new OleDbDataAdapter(commandString, connectionString);//connectionString이라는 경로와 쿼리명령을 동적할당

                OleDbCommandBuilder myCommandBuilder ///연결된 데이터베이스에서 DataSet의 변경 내용을 조정하는 데 사용되는 단일 테이블 명령을 자동으로 생성합니다
                    = new OleDbCommandBuilder(DBAdapter);

                DataSet DS = new DataSet(); //DS라는 데이터 셋 동적할당

                DBAdapter.Fill(DS, "diary"); //DS라는 데이터셋에 새로운 diary 테이블에 추가 또는 갱신하겠다고 알림.

                DataTable aTable = DS.Tables["diary"];//home테이블을 불러와 aTable을 새로 생성해서 저장

                //////////////////////////////////////////////////////////////////////////
                //////////////달력을 클릭했을때, 저장된 값이 없는 경우를 걸러내기 위한 
                if (aTable.Rows.Count == 0)
                {
                    load_flag = 0;
                    add_diary("", "0", "0", "");
                }

                for (int i = 0; i < aTable.Rows.Count; i++)
                {
                    int detect = String.Compare((select_date + UserProfile.Instance().userId), aTable.Rows[i].ItemArray[0].ToString());

                    if (detect == 0)
                    {
                        load_flag = 1;
                        add_diary(aTable.Rows[i].ItemArray[1].ToString(), aTable.Rows[i].ItemArray[5].ToString(), aTable.Rows[i].ItemArray[2].ToString(), aTable.Rows[i].ItemArray[6].ToString());
                        break;
                    }
                    else
                    {
                        load_flag = 0;
                        add_diary("", "0", "0", " ");
                    }
                }
            }
            catch (DataException DE) //DataException에러 발생확인하는 catch문
            {
                MessageBox.Show(DE.Message); //DataExpception 에러 발생시 메세지박스로 에러값을 출력해라.
            }
            catch (Exception DE) //Exception에러 발생확인하는 catch문
            {
                MessageBox.Show(DE.Message);//Expception 에러 발생시 메세지박스로 에러값을 출력해라.
            }
        }
        
    }
}
